package com.dfec.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dfec.cache.redis.Cache;
import com.dfec.cache.redis.Redis;
import com.dfec.cache.redis.UrlDataCash;
import com.dfec.utils.PropertiesUtil;
import com.dfec.utils.ResponseUtil;
import com.dfec.utils.StringUtils;

/**
 * Servlet Filter implementation class CashFilter
 */
@WebFilter(description = "缓存请求过滤", urlPatterns = { "/*" })
public class CashFilter implements Filter {
	Cache cash=null;

    /**
     * Default constructor. 
     */
    public CashFilter() {
        // TODO Auto-generated constructor stub
    	 cash = Redis.use();
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		cash=null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		 Map<String, String> map = UrlDataCash.urlKey((HttpServletRequest)request);
		 
		
		if(PropertiesUtil.config_redis_use) {
			
//			 System.out.println(UrlDataCash.url_param);
			String data=UrlDataCash.getValue(map.toString());
			    //如果值存在于redis直接返回，否则进行下一步查询
			    if(StringUtils.isNotBlank(data)) {
			    	System.out.println("redis数据检索");
			    	ResponseUtil.sendScript((HttpServletResponse)response, data);
			    }else {
			    	System.out.println("数据检索");
			    	chain.doFilter(request, response);
			    }
		}else {
			System.out.println("没有使用redis");
			chain.doFilter(request, response);
		}
	   
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	


}
